package com.gj.reggie.controller;

import com.gj.reggie.entity.R;
import com.gj.reggie.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author 郭嘉
 * @date 2022/12/30 - 11:52
 * 文件的上传和下载
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String filename="";
        try {
            //c创建一个目录对象
            File dir=new File(basePath);
            //判断前目录是否存在
            if (!dir.exists()){
                //目录不存在，需要创建
                dir.mkdir();
            }
            //获取原始文件名(但会出现覆盖问题)
            String originalFilename=file.getOriginalFilename();
            filename= StringUtils.subFileLastName(originalFilename);
            //将临时文件转存到某个位置
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    /**
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        FileInputStream inputStream=null;
        ServletOutputStream outputStream=null;
        response.setContentType("image/jpeg");
        try {
            //输入流读取文件
            inputStream=new FileInputStream(basePath+name);

            //输出流写道浏览器
            outputStream=response.getOutputStream();

            int length=0;
            byte [] buff=new byte[1024];
            while((length=inputStream.read(buff))!=-1){
                outputStream.write(buff,0,length);
                outputStream.flush();
            }

            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
